import React, { useState, useEffect } from 'react';
const { ipcRenderer } = window.require('electron');
import { UploadAndConfigPublicKey } from '../../wailsjs/go/main/App';

const ServerConnection = ({ onConnectionStatusChange, serverInfo, onServerInfoChange }) => {
  const [status, setStatus] = useState({
    message: '',
    isError: false,
    loading: false
  });

  useEffect(() => {
    // 父组件传递的 serverInfo 变化时同步到本地
    setLocalServerInfo(serverInfo);
  }, [serverInfo]);

  const [localServerInfo, setLocalServerInfo] = useState(serverInfo);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    const newInfo = {
      ...localServerInfo,
      [name]: value
    };
    setLocalServerInfo(newInfo);
    if (onServerInfoChange) {
      onServerInfoChange(newInfo);
    }
  };

  const connectSsh = async () => {
    if (!localServerInfo.host || !localServerInfo.username || !localServerInfo.password) {
      setStatus({ message: '请填写所有必填字段', isError: true, loading: false });
      return;
    }

    let timeoutId;
    try {
      setStatus({ message: '正在连接服务器...', isError: false, loading: true });
      timeoutId = setTimeout(() => {
        setStatus({ message: '连接超时，请检查网络或服务器状态', isError: true, loading: false });
        onConnectionStatusChange(false, localServerInfo);
      }, 10000);
      const result = await ipcRenderer.invoke('connect-ssh', localServerInfo);
      clearTimeout(timeoutId);
      setStatus({ message: result.message, isError: false, loading: false });
      onConnectionStatusChange(true, localServerInfo);
    } catch (error) {
      clearTimeout(timeoutId);
      setStatus({ message: `连接服务器失败: ${error.message}`, isError: true, loading: false });
      onConnectionStatusChange(false, localServerInfo);
    }
  };

  const uploadKey = async () => {
    setStatus({ message: '正在上传公钥并配置服务器...', isError: false, loading: true });
    try {
      const result = await window.backend.App.UploadPublicKey(
        serverInfo.host,
        serverInfo.port,
        serverInfo.username,
        serverInfo.password
      );
      setStatus({ message: result.message, isError: !result.success, loading: false });
    } catch (error) {
      setStatus({ message: `上传公钥失败: ${error.message}`, isError: true, loading: false });
    }
  };

  return (
    <div className="server-connection">
      <h2>服务器连接</h2>
      <div className="form-group">
        <label htmlFor="host">服务器IP</label>
        <input
          type="text"
          id="host"
          name="host"
          value={localServerInfo.host}
          onChange={handleInputChange}
          disabled={status.loading}
          placeholder="例如: 192.168.1.100"
        />
      </div>
      <div className="form-group">
        <label htmlFor="port">端口</label>
        <input
          type="text"
          id="port"
          name="port"
          value={localServerInfo.port}
          onChange={handleInputChange}
          disabled={status.loading}
          placeholder="默认: 22"
        />
      </div>
      <div className="form-group">
        <label htmlFor="username">用户名</label>
        <input
          type="text"
          id="username"
          name="username"
          value={localServerInfo.username}
          onChange={handleInputChange}
          disabled={status.loading}
          placeholder="例如: root"
        />
      </div>
      <div className="form-group">
        <label htmlFor="password">密码</label>
        <input
          type="password"
          id="password"
          name="password"
          value={localServerInfo.password}
          onChange={handleInputChange}
          disabled={status.loading}
          placeholder="输入服务器密码"
        />
      </div>
      <div className="button-group">
        <button
          onClick={connectSsh}
          disabled={
            status.loading ||
            !localServerInfo.host ||
            !localServerInfo.username ||
            !localServerInfo.password
          }
          className="primary-button"
        >
          <span role="img" aria-label="link">🔗</span> 连接服务器
        </button>
      </div>
      {status.message && (
        <div className={`status-message ${status.isError ? 'error' : ''}`}>
          {status.message}
          {status.loading && <span className="loading-spinner"></span>}
        </div>
      )}
    </div>
  );
};

export default ServerConnection; 